package ru.st.selenium.pages;

import static org.junit.Assert.assertTrue;
import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.openqa.selenium.NoSuchElementException;

import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.FindBys;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.Alert;

public class AddMoviePage extends InternalPage{
	private boolean acceptNextAlert = true;
	public boolean flagStaleness=false;
	public boolean flagWarningsPresented=false;
	public AddMoviePage(PageManager pages) {
		super(pages);
	}

	@FindBy(css="img[alt=\"Add movie\"]")
	private WebElement addMovieButton;
	
	@FindBy(xpath=".//*[@id='updateform']//label[@class='error'][not(@style)]")
	private WebElement oldElements;
	
	@FindBy(xpath=".//*[@id='updateform']/table/tbody/tr[2]/td[2]/label[not(@style)]")
	private WebElement oldElement;
	
	@FindBy(name="name")
	private WebElement titleField;
	
	@FindBy(name="duration")
	private WebElement durationField;
	
	@FindBy(name="rating")
	private WebElement ratingField;
	
	@FindBy(name="year")
	private WebElement yearField;
	
	@FindBy(name="format")
	private WebElement formatField;
	
	@FindBy(name="loandate")
	private WebElement loandateField;
	
	@FindBy(id="loaned_yes")
	private WebElement loanRadioButton;
		
	@FindBy(css="img[title=Save]")
	private WebElement saveButton;

	@FindBy(xpath=".//*[@id='results']//*[@class='movie_box']")
	private WebElement firstMovieCover;
	
	@FindBy(css="img[alt='Edit']")
	private WebElement editMovieButton;
	
	@FindBy(xpath=".//*[@id='updateform']//*[@type='text']")
	private List<WebElement> textFields;
	
	@FindBy(xpath=".//*[@id='updateform']//textarea")
	private List<WebElement> textAreas;
	
	@FindBy(css="img[alt='Remove cover']")
	private WebElement removeCoverButton;

	@FindBy(xpath=".//*[@class='photo']/img")
	private WebElement filmCoverImage;
	
	@FindBy(css="label.error[for=name]")
	private WebElement titleWarning;
	@FindBy(css="label.error[for=year]")
	private WebElement yearWarning;
	@FindBy(css="label.error[for=duration]")
	private WebElement durationWarning;
	@FindBy(css="label.error[for=rating]")
	private WebElement ratingWarning;
	@FindBy(css="label.error[for=formats]")
	private WebElement formatWarning;
	@FindBy(css="label.error[for=loandate]")
	private WebElement loandateWarning;	
	
	//click methods
	public void clickAddMovieButton () {
		addMovieButton.click();		
	}	
	public void clickSaveButton () {
		saveButton.click();
	}
	public void clickFirstMovieCover () {
		firstMovieCover.click();
	}
	public void clickEditMovieButton () {
		editMovieButton.click();
	}
	public AddMoviePage clickloanRadioButton () {
		loanRadioButton.click();
		return this;
	}
	//set field methods
	public AddMoviePage setTitle(String title) {
		titleField.clear();
		titleField.sendKeys(title);
		return this;
	}
	public AddMoviePage setDuration(String duration) {
		durationField.clear();
		durationField.sendKeys(duration);
		return this;
	}
	public AddMoviePage setRating(String rating) {
		ratingField.clear();
		ratingField.sendKeys(rating);
		return this;
	}
	public AddMoviePage setYear(String year) {
		yearField.clear();
		yearField.sendKeys(year);
		return this;
	}
	public AddMoviePage setFormat(String format) {
		formatField.clear();
		formatField.sendKeys(format);
		return this;
	}
	public AddMoviePage setloandateField (String loandate) {
		loandateField.clear();
		loandateField.sendKeys(loandate);
		return this;
	}
	// boolean methods
	public AddMoviePage isTitleWarningPresented () {
		try {
			wait.until(ExpectedConditions.stalenessOf(oldElement));
			//driver.findElement(By
			//		.xpath(".//*[@id='updateform']/table/tbody/tr[2]/td[2]/label[not(@style)]"));
			flagStaleness=false;
		}
		catch (NoSuchElementException e) {
			flagStaleness=true;
		}
		return this;
	}
	public AddMoviePage areWarningsPresented () {
		try {			
			//wait.until(ExpectedConditions.stalenessOf(oldElements)); 
			driver.findElement(By
					.xpath(".//*[@id='updateform']//label[@class='error'][not(@style)]"));
			flagWarningsPresented = true;
		}
		catch (NoSuchElementException e) {
			flagWarningsPresented = false;
		}
		return this;
	}
	public boolean areAllTextFieldsEmpty () {
		boolean emptyFlag1=true;
	    for (WebElement item : textFields) {
	        if (!item.getAttribute("value").matches("")) {
	        	emptyFlag1=false; 
	        }
	    }
	    boolean emptyFlag2=true;
	    for (WebElement item : textAreas) {
	    	if (!item.getAttribute("value").matches("")) {
	        	emptyFlag2=false; 
	        }
	    }
	    return emptyFlag1 && emptyFlag2;    
	}
	public boolean doesCoverImageExist () {
		try {
			filmCoverImage.isDisplayed();
			return true;
		}
		catch (NoSuchElementException t) {
			return false;
		}
	}
	public boolean areTheseWarningsPresented (ArrayList<String> warnings) {
		boolean methodFlag=false;
		for (String str : warnings) {			
			boolean iteratorFlag=false;
			switch (str) {
			case "title":
				iteratorFlag = titleWarning.isDisplayed() ? true : false;
				break;
			case "year":
				iteratorFlag = yearWarning.isDisplayed() ? true : false;
				break;
			case "duration":
				iteratorFlag = durationWarning.isDisplayed() ? true : false;
				break;
			case "rating":
				iteratorFlag = ratingWarning.isDisplayed() ? true : false;
				break;
			case "loandate":
				iteratorFlag = loandateWarning.isDisplayed() ? true : false;
				break;
			case "format":
				iteratorFlag = formatWarning.isDisplayed() ? true : false;
				break;			
			default:
				System.out.println("No such warning element");				
				break;
			}
			if (iteratorFlag==true){methodFlag=true;}
			 
		}
		return methodFlag;
	}
	// other methods
	public void clearEditingFields () {
	    for (WebElement item : textFields) {
	        item.clear();
	    }
	    for (WebElement item : textAreas) {
	        item.clear();
	    }
	    return;
	}
	public void removeFilmCover () {		
		try {
				removeCoverButton.click();
				assertTrue(closeAlertAndGetItsText()
						.matches("^Are you sure you want to remove this cover[\\s\\S]$"));
		}
		catch (NoSuchElementException t) {			
		}

	}
	private String closeAlertAndGetItsText() {
	    try {
	    	Alert alert = driver.switchTo().alert();
		    String alertText = alert.getText();
		    if (acceptNextAlert) {
		        alert.accept();
		    } else {
		        alert.dismiss();
		    }
		    return alertText;
		    } finally {
		      acceptNextAlert = true;
		    }
	}
	private boolean isElementPresent(By by) {
		    try {
		      driver.findElement(by);
		      return true;
		    } catch (NoSuchElementException e) {
		      return false;
		    }
	}
}
